{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Readout: Time-Series Analysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from cirq_internal import io as ciio\n",
    "from cirq_internal.benchmarking.experiments.readout_scan.readout \\\n",
    "    import EXPERIMENT_NAME, DEFAULT_BASE_DIR\n",
    "EXPERIMENT_NAME, DEFAULT_BASE_DIR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "records = []\n",
    "# Load all data, do some light processing\n",
    "for record in ciio.iterload_records(dataset_id='*', base_dir=DEFAULT_BASE_DIR):\n",
    "    \n",
    "    # Unwrap BitstringArray into np.ndarray\n",
    "    all_bitstrings = [ba.bitstrings for ba in record['all_bitstrings']]\n",
    "    \n",
    "    # Compute <Z>\n",
    "    record['z_vals'] = [np.mean((-1)**bitstrings, axis=0).item() for bitstrings in all_bitstrings]\n",
    "    \n",
    "    # Don't need to carry around the full array of bits anymore\n",
    "    del record['all_bitstrings']\n",
    "    records.append(record)\n",
    "    \n",
    "df = pd.DataFrame(records)\n",
    "print(len(df))\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Query relevant data\n",
    "# Select and drop: device_name, simulator\n",
    "# Set index\n",
    "\n",
    "dfb = df\n",
    "dfb = dfb[dfb['device_name'] == 'Sycamore23']\n",
    "dfb = dfb.drop('device_name', axis=1)\n",
    "dfb = dfb[~dfb['simulator']]\n",
    "dfb = dfb.drop('simulator', axis=1)\n",
    "dfb['timestamp'] = pd.to_datetime(dfb['timestamp'])\n",
    "dfb = dfb.sort_values(by=['data_collection_id', 'qubit'])\n",
    "dfb = dfb.groupby('data_collection_id').filter(lambda x: len(x) > 2)\n",
    "dfb = dfb.set_index(['data_collection_id', 'qubit'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "for dc_id in dfb.index.levels[0]:\n",
    "    dfc = dfb.loc[dc_id]\n",
    "    plt.axhline(-1, color='grey')\n",
    "    plt.axhline(1, color='grey')\n",
    "    for q, row in dfc.iterrows():\n",
    "        plt.plot(row['thetas'], row['z_vals'], label=f'{q}')\n",
    "    plt.ylim(-1.1, 1.1)\n",
    "        \n",
    "    #plt.legend(loc='best')\n",
    "    plt.title(dc_id)\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "eps = 1e-5\n",
    "\n",
    "p00s = []\n",
    "p11s = []\n",
    "for i, row in dfb.iterrows():\n",
    "    ti1 = np.where(np.abs(np.asarray(row['thetas']) - 0) < eps)[0][0]\n",
    "    ti2 = np.where(np.abs(np.asarray(row['thetas']) - np.pi)<eps)[0][0]\n",
    "    p00 = row['z_vals'][ti1]\n",
    "    p11 = -1*row['z_vals'][ti2]\n",
    "    p00s.append(p00)\n",
    "    p11s.append(p11)\n",
    "\n",
    "dfb['p00'] = p00s\n",
    "dfb['p11'] = p11s\n",
    "dfb.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "import pandas as pd\n",
    "dfc = dfb.reset_index()\n",
    "dfc = pd.melt(dfc, id_vars=['data_collection_id', 'qubit'], value_vars=['p00', 'p11'])\n",
    "\n",
    "# Outlier\n",
    "dfc = dfc[dfc['value'] > 0.5]\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(7,5))\n",
    "sns.violinplot(dfc['data_collection_id'], dfc['value'], hue=dfc['variable'], split=True, ax=ax, cut=0)\n",
    "ax.legend(loc='best', fontsize=16)\n",
    "ax.set_xlabel(None)\n",
    "ax.set_ylabel(None)\n",
    "fig.autofmt_xdate()\n",
    "fig.tight_layout()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "for dc_id in dfb.index.levels[0]:\n",
    "    dfc = dfb.loc[dc_id]    \n",
    "    fig, ax = plt.subplots(figsize=(7,5))\n",
    "    ax.scatter(dfc['timestamp'], dfc['p00'])\n",
    "    ax.scatter(dfc['timestamp'], dfc['p11'])\n",
    "    ax.set_xlim((dfc['timestamp'].min(), dfc['timestamp'].max()))\n",
    "    #fig.autofmt_xdate()\n",
    "    fig.tight_layout()\n",
    "    plt.show()"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}